package com.dogkr.server.web;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dogkr.common.Constants;
import com.dogkr.common.ServerAction;
import com.dogkr.server.entity.User;
import com.dogkr.server.service.UserService;
import com.sean.common.utils.StringUtils;


// 设置Struts2注解
@ParentPackage(value = "login-default")
@Namespace(value = "/user")
@ResultPath("/WEB-INF/jsps")
// 页面文件空间
@Results({
	@Result(name = "info", location = "info.jsp"),
	@Result(name = "manage", location = "manage.jsp")
})
public class UserAction extends ServerAction {
	private static final long serialVersionUID = 1L;
	
	private User user;
	
	@Autowired
	private UserService userService;
	
	@Action(value = "info")
	public String info() {
		put("fileSize", Constants.UPLOAD_FILE_SIZE);
		return "info";
	}
	
	@Action(value = "manage")
	public String manage() {
		return "manage";
	}

	@Action(value = "get")
	public void get() {
		outJson(this.getLoginUser());
	}
	
	@Action(value = "saveinfo")
	public void saveInfo() {
		User loginUser = this.getLoginUser();
		user.setId(loginUser.getId());
		userService.updateUserInfo(user, loginUser.getUserPhotoPath());
		loginUser.updateInfo(user);
		if(StringUtils.isNotBlank(user.getUserPhotoPath())) {
			loginUser.setUserPhotoPath(user.getUserPhotoPath());
		}
		outJson(res);
	}
	
	@Action(value = "resetpass")
	public void resetPassword() {
		String oldPass = this.get("oldPass");
		if(StringUtils.isNotBlank(user.getLoginPassword())) {
			user.setLoginPassword(DigestUtils.md5Hex(user.getLoginPassword()));
			if(this.getLoginUser().getLoginPassword().equals(DigestUtils.md5Hex(oldPass))) {
				user.setId(this.getLoginUser().getId());
				userService.resetPassword(user);
				this.getLoginUser().setLoginPassword(user.getLoginPassword());
			} else {
				res = this.getErrRes("原始密码错误!");
			}
		} else {
			res = this.getErrRes();
		}
		outJson(res);
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
